/**
 * 通用上传文件对话框
 * @author chaowangbang
 * @since 2012-1-1
 */

Ccay.Module.define("Ccay.Upload.Custom",function(page,$S){
	var parametersMap = new Ccay.HashMap();
	page.init=function(uploadParam){
		if(parseInt($.browser.version) < 10){
			$('#'+uploadParam.customId).hide();
		}
		var  uploadParameters = parametersMap.get(uploadParam.customId)
		if(!uploadParameters){
			uploadParameters = uploadParam;
			parametersMap.put(uploadParam.customId,uploadParam);
		}
		
		if(!uploadParameters.initCount){
			uploadParameters.initCount = 0;
		}
		
		uploadParameters.uploadedCount = 0 ;

		//如果需要批次号，并且批次号尚未生成
		if(uploadParam.needBatchId && !uploadParam.batchId){
			uploadParam.query = uploadParam.query + "&needBatchId=1";
		}
		//Ccay.Core.log(uploadParam); 
		Ccay.doGet("services/ccay/upload/support/{0}".formatURI(uploadParam.uploadType),uploadParam.query,function(uploadSetting){			
			Ccay.Core.log("batch id got:" +uploadSetting.batchId );
			//Ccay.Core.log("batch id in param :" +uploadParam.batchId );
			
			if(!uploadParam.batchId && uploadSetting.batchId){
				//Ccay.Core.log("init batch id for this upload:" +uploadSetting.batchId) ;
				uploadParam.batchId = uploadSetting.batchId;
			}
			
			uploadParameters.maxFileCount = uploadSetting.maxFileCount;
			
			initComponent(uploadParam,uploadSetting);
		},function(textStatus, errorThrown){
			$S("#uploader").html($.i18n.prop("ccay.common.message.unknownError").encode());
		});
		
	};
	

	
	/**
	 *	转化格式
	 */
	function convert(fileTypes){
		var p = navigator.platform;
		if(p && p.indexOf("Linux")==0){
			var types = fileTypes.join(",")
			return [{title : types, extensions : "*"}];
		}else{
			var types = fileTypes.join(",")
			return [{title : types, extensions : types}];
		}
	};
	
	function initComponent(uploadParam,uploadSetting){
		plupload.addI18n({
		    'Select files' : $.i18n.prop("ccay.upload.label.browse"),
		    'Add files to the upload queue and click the start button.' : $.i18n.prop("ccay.upload.label.browseAndStart"),
		    'Filename' : $.i18n.prop("ccay.upload.label.fileName"),
		    'Status' : $.i18n.prop("ccay.upload.label.status"),
		    'Size' : $.i18n.prop("ccay.upload.label.size"),
		    'Add Files' :$.i18n.prop("ccay.upload.label.browse"),
		    'Stop current upload' : $.i18n.prop("ccay.upload.label.stop"),
		    'Start uploading queue' : $.i18n.prop("ccay.upload.label.startQuere"),
		    'Drag files here.' : $.i18n.prop("ccay.upload.label.dragToHere") ,
		    'Start Upload': $.i18n.prop("ccay.upload.label.start"),
		    'Uploaded %d/%d files': $.i18n.prop("ccay.upload.label.uploaded"),
		    'Error: File too large: ': $.i18n.prop("ccay.upload.message.fileTooLarge"),
			'Error: Invalid file extension: ': $.i18n.prop("ccay.upload.message.fileTypeInvalid"),
			'File extension error.': $.i18n.prop("ccay.upload.message.fileTypeInvalid"),
			'File size error.': $.i18n.prop("ccay.upload.message.fileSizeError"),
			'File count error.': $.i18n.prop("ccay.upload.message.fileCountError"),
			'Using runtime:': $.i18n.prop("ccay.upload.message.usingRuntime")
		});
		var uploadUrl="servlet/upload?ulType={0}&batchId={1}&".formatURI(uploadParam.uploadType, uploadParam.batchId) + uploadParam.query; 
		//区分子应用
		if(uploadParam.currentContext){
			uploadUrl = "{0}/{1}".formatValue(uploadParam.currentContext,uploadUrl);
		}
		
		var uploader = new plupload.Uploader({
			runtimes : 'html5,flash,silverlight,html4',
			browse_button : uploadParam.customId, // you can pass in id...
			container:"container",
			unique_names : true,			
			max_file_count: uploadSetting.maxFileCount,
			multi_selection:(uploadSetting.maxFileCount>1),
			filters : convert(uploadSetting.fileTypesAllowed),
			url :uploadUrl,
			init: {
				FilesAdded:fileAdded,
				UploadComplete:uploadComplete,
				UploadProgress: uploadProgress,
				FileUploaded:fileUploaded,
				Error: fileError,
				PostInit: function() {
					$("#"+uploadParam.customId).show();
				}
			}
		});
		uploader.init();
		//对上传要求过滤类型为xlsm 时做处理
		if(uploadSetting.fileTypesAllowed.toString().indexOf("xlsm")!= -1){
           var div = $("#"+uploader.id+"_html5_container"), input = div.find("input[type=file][accept]");
           if(input.length){
                input.attr("accept",input.attr("accept") + ",application/vnd.ms-excel.sheet.macroEnabled.12");
           }
        }
	};
	
	function fileAdded(uploader,files){
		var  uploadParameters = parametersMap.get(uploader.settings.browse_button);
		if(uploadParameters.initCount + uploader.files.length > uploadParameters.maxFileCount){
			for(var x=0;x < files.length ; x++){
				uploader.removeFile(files[x]);
			}
			Ccay.UI.showMessage($.i18n.prop("ccay.upload.message.overMaxCount").formatValue(uploadParameters.maxFileCount),"error");
			return;
		}
		var zeroFile = false;
		for(var x=0;x < files.length ; x++){
			if(!files[x] || files[x].size == 0){
				uploader.removeFile(files[x]);
				zeroFile = true;
			}
		}
		if(zeroFile){
			Ccay.UI.showMessage($.i18n.prop("ccay.upload.message.filesZero"));
			return;
		}
		if(uploadParameters.fileContentId){
			plupload.each(files, function(file) {
				$('#'+uploadParameters.fileContentId).append('<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>');
			});	  
		}
		if(uploadParameters.fileAddedCallback){
			uploadParameters.fileAddedCallback(files);
		}
		uploader.start();
	}
	
	
	function filesRemoved(uploader,files){
		Ccay.Core.log("files removed:" +files.length);
	}
	
	function fileError(uploader,error){
		Ccay.Core.log("files upload error:" +error.message);
		alert(error.message);
	}
	
	function uploadComplete(uploader, files){
		if(uploader.files.length ==0){
			return ;
		}
		var  uploadParameters = parametersMap.get(uploader.settings.browse_button);
		if(uploadParameters.completeCallback){
			uploadParameters.completeCallback(files, uploadParameters.batchId, uploadParameters.userObject);
		}
	};

	
	function fileUploaded(uploader, file, serverResponse){
		var serverData = eval("(" + serverResponse.response +")");
		Ccay.Core.log("After Upload Complete: " + file.name);
		
		if(serverData && serverData.httpCode){
			Ccay.Core.log("Error: " + serverData.message);			
			
			if(serverData.message && serverData.message.indexOf("{") == 0){
				var msg = Ccay.DataHelper.toJson(serverData.message);
				alert($.i18n.prop("ccay.upload.message.failed").formatValue(file.name, msg.fieldErrors[0].messages));
			}else if(serverData.message && serverData.message.length >0){
				alert($.i18n.prop("ccay.upload.message.failed").formatValue(file.name,serverData.message));
			} else {
				alert($.i18n.prop("ccay.upload.message.failed").formatValue(file.name,"Unknown."))
			}
			uploader.removeFile(file);
			$("#"+file.id).remove();
			return ;
		}
		var  uploadParameters = parametersMap.get(uploader.settings.browse_button);
		if(uploadParameters.callback){
			uploadParameters.callback(file, serverData, uploadParameters.batchId, uploadParameters.userObject);
		} 
	}
	function uploadProgress(uploader, file){
		var  uploadParameters = parametersMap.get(uploader.settings.browse_button);
		if(uploadParameters.progressCallback){
			uploadParameters.progressCallback(file);
			return;
		}
		$("b", $("#"+file.id)).each(function(e){
		     this.innerHTML = '<span>' + file.percent + "%</span>";
		});
	}
});